# -*- coding: utf-8 -*-

from odoo import models, fields, api
from odoo.exceptions import ValidationError


class Inspection(models.Model):
    """设备巡检模型"""
    _name = 'device.inspection'
    _description = '设备巡检管理'
    _order = 'inspection_date desc, id desc'
    _rec_name = 'display_name'
    _inherit = ['device.permission.mixin']
    
    # 关联设备
    equipment_id = fields.Many2one('device.equipment', '设备', required=True, ondelete='cascade')
    equipment_name = fields.Char('设备名称', related='equipment_id.name', store=True)
    equipment_code = fields.Char('设备编号', related='equipment_id.code', store=True)
    equipment_category = fields.Char('设备类别', related='equipment_id.category_name', store=True)
    equipment_model = fields.Char('设备型号', related='equipment_id.model', store=True)
    
    # 巡检基础信息
    inspection_date = fields.Date('巡检日期', required=True, default=fields.Date.today)
    inspection_content = fields.Text('巡检内容', required=True)
    
    # 巡检人员
    inspector_id = fields.Many2one('device.user', '巡检人', required=True)
    inspector_name = fields.Char('巡检人姓名', related='inspector_id.nick_name', store=True)
    
    # 巡检类型
    inspection_type = fields.Selection([
        ('routine', '例行巡检'),
        ('special', '专项巡检'),
        ('emergency', '紧急巡检'),
        ('maintenance', '维保巡检')
    ], string='巡检类型', default='routine', required=True)
    
    # 巡检状态
    status = fields.Selection([
        ('planned', '计划中'),
        ('ongoing', '进行中'),
        ('completed', '已完成'),
        ('abnormal', '异常')
    ], string='巡检状态', default='planned', required=True)
    
    # 巡检结果
    result = fields.Selection([
        ('normal', '正常'),
        ('warning', '预警'),
        ('abnormal', '异常'),
        ('fault', '故障')
    ], string='巡检结果', default='normal')
    
    # 问题描述
    problem_description = fields.Text('问题描述')
    solution = fields.Text('解决方案')
    
    # 巡检时长
    duration_minutes = fields.Integer('巡检时长（分钟）', default=30)
    
    # 文件附件
    attachment_ids = fields.One2many('ir.attachment', 'res_id', 
                                   domain=[('res_model', '=', 'device.inspection')], 
                                   string='巡检附件')
    
    # 附件URL字段 - 存储通过公共上传接口上传的文件URL
    attachment_urls = fields.Text('附件URL列表', help='存储文件URL，多个URL用换行分隔')
    inspection_report_url = fields.Char('巡检报告URL', help='巡检报告文件的URL')
    image_urls = fields.Text('现场图片URL', help='巡检现场图片的URL，多个URL用换行分隔')
    video_urls = fields.Text('视频记录URL', help='巡检视频记录的URL，多个URL用换行分隔')
    
    # 显示名称
    display_name = fields.Char('显示名称', compute='_compute_display_name', store=True)
    
    # 创建和修改信息
    create_time = fields.Datetime('创建时间', default=fields.Datetime.now)
    update_time = fields.Datetime('更新时间', default=fields.Datetime.now)
    create_by = fields.Char('创建者')
    update_by = fields.Char('更新者')
    remark = fields.Text('备注')
    
    @api.depends('equipment_id', 'inspection_date', 'inspector_id')
    def _compute_display_name(self):
        for record in self:
            if record.equipment_id and record.inspection_date:
                inspector_name = record.inspector_name or '未知'
                record.display_name = f"{record.equipment_id.name} - {inspector_name} ({record.inspection_date})"
            else:
                record.display_name = "新巡检记录"
    
    @api.constrains('duration_minutes')
    def _check_duration_minutes(self):
        for record in self:
            if record.duration_minutes <= 0:
                raise ValidationError('巡检时长必须大于0分钟。')
    
    @api.model_create_multi
    def create(self, vals_list):
        for vals in vals_list:
            vals['create_time'] = fields.Datetime.now()
            if self.env.user:
                vals['create_by'] = self.env.user.name
        return super().create(vals_list)
    
    def write(self, vals):
        vals['update_time'] = fields.Datetime.now()
        if self.env.user:
            vals['update_by'] = self.env.user.name
        return super().write(vals)
    
    def action_start_inspection(self):
        """开始巡检"""
        self.write({'status': 'ongoing'})
    
    def action_complete_inspection(self):
        """完成巡检"""
        self.write({'status': 'completed'})
    
    def action_mark_abnormal(self):
        """标记异常"""
        self.write({'status': 'abnormal', 'result': 'abnormal'})
